// src/main/java/com/lyj/service/impl/FamilyServiceImpl.java
package com.lyj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lyj.exception.BaseException;
import com.lyj.mapper.FamilyMapper;
import com.lyj.mapper.FamilyMemberMapper;
import com.lyj.pojo.Family;
import com.lyj.pojo.FamilyMember;
import com.lyj.pojo.dto.FamilyUpdateNameDTO;
import com.lyj.service.FamilyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.UUID;

@Service
public class FamilyServiceImpl implements FamilyService {

    @Autowired
    private FamilyMapper familyMapper;

    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Override
    public String generateShareCode(Integer userId) {
        // 1. 验证用户是否为管理员
        FamilyMember member = getFamilyMemberByUserId(userId);
        if (!"管理员".equals(member.getRole())) {
            throw new BaseException("无权限生成邀请码");
        }

        // 2. 生成新的邀请码
        String shareCode = generateUniqueShareCode();

        // 3. 更新家庭邀请码
        Family family = familyMapper.selectById(member.getFamilyId());
        family.setShareCode(shareCode);
        familyMapper.updateById(family);

        return shareCode;
    }

    @Transactional
    @Override
    public void updateMemberRole(Integer operatorId, Integer memberId, String role) {
        // 1. 验证操作者是否为管理员
        FamilyMember operator = getFamilyMemberByUserId(operatorId);
        if (!"管理员".equals(operator.getRole())) {
            throw new BaseException("无权限修改角色");
        }

        // 2. 验证目标成员是否存在且属于同一家庭
        FamilyMember targetMember = familyMemberMapper.selectById(memberId);
        if (targetMember == null) {
            throw new BaseException("成员不存在");
        }
        if (!targetMember.getFamilyId().equals(operator.getFamilyId())) {
            throw new BaseException("不能操作其他家庭的成员");
        }

        // 3. 执行角色更新
        targetMember.setRole(role);
        familyMemberMapper.updateById(targetMember);
    }

    @Transactional
    @Override
    public void deleteMember(Integer operatorId, Integer memberId) {
        // 1. 验证操作者是否为管理员
        FamilyMember operator = getFamilyMemberByUserId(operatorId);
        if (!"管理员".equals(operator.getRole())) {
            throw new BaseException("无权限删除成员");
        }

        // 2. 验证目标成员是否存在且属于同一家庭
        FamilyMember targetMember = familyMemberMapper.selectById(memberId);
        if (targetMember == null) {
            throw new BaseException("成员不存在");
        }
        if (!targetMember.getFamilyId().equals(operator.getFamilyId())) {
            throw new BaseException("不能删除其他家庭的成员");
        }

        // 3. 防止删除自己
        if (targetMember.getUserId().equals(operatorId)) {
            throw new BaseException("不能删除自己");
        }

        // 4. 执行删除
        familyMemberMapper.deleteById(memberId);
    }

    @Override
    public void updateFamilyName(Integer operatorId, FamilyUpdateNameDTO dto) {
        // 1. 验证操作者是否为管理员
        FamilyMember operator = getFamilyMemberByUserId(operatorId);
        if (!"管理员".equals(operator.getRole())) {
            throw new BaseException("无权限修改家庭名称");
        }

        // 2. 验证家庭是否存在且属于当前用户家庭
        Family family = familyMapper.selectById(dto.getFamilyId());
        if (family == null) {
            throw new BaseException("家庭不存在");
        }
        if (!family.getFamilyId().equals(operator.getFamilyId())) {
            throw new BaseException("无权限操作此家庭");
        }

        // 3. 更新家庭名称
        family.setFamilyName(dto.getFamilyName());
        familyMapper.updateById(family);
    }

    /**
     * 生成唯一的家庭邀请码
     */
    private String generateUniqueShareCode() {
        String code = UUID.randomUUID().toString().substring(0, 8).toUpperCase();
        if (familyMapper.selectByShareCode(code) != null) {
            return generateUniqueShareCode(); // 递归生成新的
        }
        return code;
    }

    /**
     * 根据用户ID查询家庭成员信息
     */
    private FamilyMember getFamilyMemberByUserId(Integer userId) {
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getUserId, userId);
        FamilyMember member = familyMemberMapper.selectOne(queryWrapper);
        if (member == null) {
            throw new BaseException("用户未加入任何家庭");
        }
        return member;
    }
}